package cn.edu.uestc.framework.auth.aspect;

import cn.edu.uestc.cwdsj.utils.constant.RoleConstants;
import cn.edu.uestc.framework.auth.annotation.TKRoleRequired;
import cn.edu.uestc.framework.exception.TKBusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 用于检查权限的切面
 * Created by Eric on 2017/7/3.
 */
@Aspect
public class AuthCheckAspect {
    private TKBusinessException noLogin = new TKBusinessException(null, 20001, null);
    private TKBusinessException needHigherPrivilege = new TKBusinessException(null, 20002, null);
    private static final String SESSION_KEY_UID = "uid";

    @Resource
    private HttpSession session;

    @Before("execution (* cn.edu.uestc.cwdsj.service.*.*(..))")
    public void checkRole(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        TKRoleRequired annotation = method.getAnnotation(TKRoleRequired.class);

        if (annotation == null) {
            throw needHigherPrivilege;
        }
        String roleId = annotation.roleId();
        String uid = (String) session.getAttribute(SESSION_KEY_UID);

        if (!roleId.equals(RoleConstants.ROLE_ANY) && uid == null) {
            throw noLogin;
        }
    }
}
